<template>
  <div class="log-viewer">
    <div class="log-header">
      <h2>迁移SQL操作日志</h2>
      <div class="log-controls">
        <el-button type="primary" @click="refreshLogs">刷新日志</el-button>
        <el-select v-model="selectedDate" placeholder="选择日期" @change="loadLogs">
          <el-option 
            v-for="date in availableDates" 
            :key="date" 
            :label="date" 
            :value="date" 
          />
        </el-select>
      </div>
    </div>
    <div class="log-content">
      <div v-if="loading" class="loading-indicator">
        <el-icon class="is-loading"><Loading /></el-icon>
        加载中...
      </div>
      <div v-else-if="logEntries.length === 0" class="no-logs">
        没有找到日志记录
      </div>
      <div v-else class="log-entries">
        <div v-for="(entry, index) in logEntries" :key="index" class="log-entry" @click="toggleDetails(entry)">
          <div class="log-summary">
            <span class="log-timestamp">{{ formatTime(entry.timestamp) }}</span>
            <span class="log-method">表: {{ entry.tableName }}</span>
            <span class="log-status">SQL数: {{ entry.sqls.length }}</span>
            <el-icon class="log-toggle-icon">
              <ArrowDown v-if="!entry.showDetails" />
              <ArrowUp v-else />
            </el-icon>
          </div>
          <div v-if="entry.showDetails" class="log-details">
            <ul>
              <li v-for="(sql, i) in entry.sqls" :key="i">
                <code>{{ sql.sql }}</code>
                <span v-if="sql.params && sql.params.length"> | 参数: {{ sql.params }}</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { ArrowDown, ArrowUp, Loading } from '@element-plus/icons-vue';

// 新增：支持外部传入最新日志
const props = defineProps({
  latestLog: { type: Object, default: null },
});

const logEntries = ref([]);
const availableDates = ref([]);
const selectedDate = ref('');
const loading = ref(false);

onMounted(() => {
  loadAvailableDates();
});

// 监听外部传入的最新日志
watch(
  () => props.latestLog,
  (val) => {
    if (val && val.sqls && val.sqls.length) {
      // 置顶显示
      logEntries.value.unshift({ ...val, showDetails: true });
    }
  }
);

function getAllSqlLogs() {
  const logs = JSON.parse(localStorage.getItem('migration_sql_logs') || '[]');
  // 按天分组
  const map = {};
  logs.forEach(log => {
    const d = new Date(log.timestamp);
    const dateStr = d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + String(d.getDate()).padStart(2,'0');
    if (!map[dateStr]) map[dateStr] = [];
    map[dateStr].push({ ...log, showDetails: false });
  });
  return map;
}

function loadAvailableDates() {
  const map = getAllSqlLogs();
  availableDates.value = Object.keys(map).sort((a,b)=>b.localeCompare(a));
  if (availableDates.value.length > 0) {
    selectedDate.value = availableDates.value[0];
    loadLogs();
  }
}

function loadLogs() {
  if (!selectedDate.value) return;
  loading.value = true;
  setTimeout(() => {
    const map = getAllSqlLogs();
    logEntries.value = (map[selectedDate.value] || []);
    loading.value = false;
  }, 100);
}

function toggleDetails(entry) {
  entry.showDetails = !entry.showDetails;
}

function refreshLogs() {
  loadLogs();
}

function formatTime(timestamp) {
  const date = new Date(timestamp);
  return date.toLocaleString();
}
</script>

<style scoped>
.log-viewer {
  height: 100%;
  display: flex;
  flex-direction: column;
  color: #ecf0f1;
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #34495e;
  margin-bottom: 15px;
}

.log-header h2 {
  margin: 0;
  font-size: 20px;
}

.log-controls {
  display: flex;
  gap: 15px;
}

.log-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  background-color: #1a2530;
  border-radius: 6px;
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #3498db;
  font-size: 16px;
}

.no-logs {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #7f8c8d;
}

.log-entries {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.log-entry {
  background-color: #2c3e50;
  border-radius: 6px;
  padding: 12px 15px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.log-entry:hover {
  background-color: #34495e;
}

.log-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.log-timestamp {
  font-size: 12px;
  color: #95a5a6;
  min-width: 90px;
}

.log-method {
  flex: 1;
  font-weight: 500;
  color: #3498db;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.log-status {
  min-width: 180px;
  text-align: right;
  color: #2ecc71;
}

.log-entry.is-response .log-status {
  color: #e74c3c;
}

.log-toggle-icon {
  margin-left: 10px;
  color: #7f8c8d;
}

.log-details {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #34495e;
}

pre {
  font-size: 12px;
  color: #bdc3c7;
  background-color: #1a2530;
  padding: 10px;
  border-radius: 4px;
  max-height: 300px;
  overflow: auto;
  white-space: pre-wrap;
}
</style>